import React, { useState, useRef, useEffect } from 'react';
import { Input, Button, List, Avatar, Typography, Space, Tag, Card, Tooltip, message, Modal } from 'antd';
import { SendOutlined, UserOutlined, RobotOutlined, EditOutlined, CloseOutlined, ClockCircleOutlined, ExclamationCircleOutlined, CheckOutlined } from '@ant-design/icons';
import { Socket } from 'socket.io-client';
import { Conversation, ChatMessage } from '../../KimiChat';
import './ChatContent.scss';

const { TextArea } = Input;
const { Text, Paragraph } = Typography;

interface ChatContentProps {
    conversation: Conversation | undefined;
    onSendMessage: (content: string) => void;
    onAuditAction: (messageId: string, action: 'approve' | 'reject') => void;
    isConnected: boolean;
    socket: React.MutableRefObject<Socket | null>;
}

const ChatContent: React.FC<ChatContentProps> = ({
    conversation,
    onSendMessage,
    onAuditAction,
    isConnected,
    socket
}) => {
    const [inputValue, setInputValue] = useState('');
    const [isComposing, setIsComposing] = useState(false);
    const [editModalVisible, setEditModalVisible] = useState(false);
    const [editingMessage, setEditingMessage] = useState<ChatMessage | null>(null);
    const [editContent, setEditContent] = useState('');
    const messagesEndRef = useRef<HTMLDivElement>(null);
    const inputRef = useRef<any>(null);

    // 自动滚动到底部
    const scrollToBottom = () => {
        messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    };

    useEffect(() => {
        scrollToBottom();
    }, [conversation?.messages]);

    // 发送消息
    const handleSend = () => {
        if (!inputValue.trim() || !isConnected) {
            if (!isConnected) {
                message.warning('请等待连接建立后再发送消息');
            }
            return;
        }

        onSendMessage(inputValue.trim());
        setInputValue('');
        inputRef.current?.focus();
    };

    // 处理键盘事件
    const handleKeyPress = (e: React.KeyboardEvent) => {
        if (e.key === 'Enter' && !e.shiftKey && !isComposing) {
            e.preventDefault();
            handleSend();
        }
    };

    // 处理审核操作
    const handleAudit = (messageId: string, action: 'approve' | 'reject') => {
        onAuditAction(messageId, action);
    };

    // 处理编辑操作
    const handleEdit = (message: ChatMessage) => {
        setEditingMessage(message);
        setEditContent(message.content);
        setEditModalVisible(true);
    };

    // 处理忽略操作
    const handleIgnore = (messageId: string) => {
        onAuditAction(messageId, 'reject');
    };

    // 提交编辑内容
    const handleSubmitEdit = () => {
        if (!editingMessage || !socket.current) {
            message.error('提交失败，请检查连接状态');
            return;
        }

        // 发送编辑结果到服务端
        socket.current.emit('match_update', {
            messageId: editingMessage.id,
            content: editContent,
            conversationId: editingMessage.conversationId
        });

        // 关闭弹窗
        setEditModalVisible(false);
        setEditingMessage(null);
        setEditContent('');
        
        message.success('编辑内容已提交');
    };

    // 取消编辑
    const handleCancelEdit = () => {
        setEditModalVisible(false);
        setEditingMessage(null);
        setEditContent('');
    };

    // 获取消息状态标签
    const getStatusTag = (message: ChatMessage) => {
        if (message.messageType !== 'audit') return null;

        switch (message.status) {
            case 'pending':
                return (
                    <Tag icon={<ClockCircleOutlined />} color="orange">
                        待审核
                    </Tag>
                );
            case 'approved':
                return (
                    <Tag icon={<CheckOutlined />} color="green">
                        已通过
                    </Tag>
                );
            case 'rejected':
                return (
                    <Tag icon={<CloseOutlined />} color="red">
                        已拒绝
                    </Tag>
                );
            default:
                return null;
        }
    };

    // 获取消息图标
    const getMessageIcon = (message: ChatMessage) => {
        switch (message.type) {
            case 'user':
                return <Avatar icon={<UserOutlined />} className="chat-content__avatar chat-content__avatar--user" />;
            case 'assistant':
                return <Avatar icon={<RobotOutlined />} className="chat-content__avatar chat-content__avatar--assistant" />;
            case 'system':
                return <Avatar icon={<ExclamationCircleOutlined />} className="chat-content__avatar chat-content__avatar--system" />;
            default:
                return <Avatar icon={<RobotOutlined />} className="chat-content__avatar" />;
        }
    };

    // 格式化时间
    const formatTime = (date: Date) => {
        return date.toLocaleTimeString('zh-CN', {
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });
    };

    // 渲染消息内容
    const renderMessageContent = (message: ChatMessage) => {
        const isAuditMessage = message.messageType === 'audit';
        const isPending = message.status === 'pending';
        
        return (
            <div className={`chat-content__message-wrapper chat-content__message-wrapper--${message.type}`}>
                <div className="chat-content__message-header">
                    <Space>
                        {getMessageIcon(message)}
                        <Text strong className="chat-content__sender">
                            {message.type === 'user' ? '用户' : 
                             message.type === 'assistant' ? '助手' : '系统'}
                        </Text>
                        <Text type="secondary" className="chat-content__time">
                            {formatTime(message.timestamp)}
                        </Text>
                        {getStatusTag(message)}
                    </Space>
                </div>
                
                <Card 
                    className={`chat-content__message-card chat-content__message-card--${message.type} ${
                        isAuditMessage ? 'chat-content__message-card--audit' : ''
                    }`}
                    bodyStyle={{ padding: '12px 16px' }}
                >
                    <Paragraph className="chat-content__message-text">
                        {message.content}
                    </Paragraph>
                    
                    {isAuditMessage && isPending && (
                        <div className="chat-content__audit-actions">
                            <Space>
                                <Button
                                    type="primary"
                                    icon={<EditOutlined />}
                                    onClick={() => handleEdit(message)}
                                    className="chat-content__edit-btn"
                                    size="small"
                                >
                                    编辑
                                </Button>
                                <Button
                                    danger
                                    icon={<CloseOutlined />}
                                    onClick={() => handleIgnore(message.id)}
                                    className="chat-content__ignore-btn"
                                    size="small"
                                >
                                    忽略
                                </Button>
                            </Space>
                        </div>
                    )}
                </Card>
            </div>
        );
    };

    return (
        <div className="chat-content">
            {/* 消息显示区域 */}
            <div className="chat-content__messages">
                {!conversation ? (
                    <div className="chat-content__empty">
                        <div className="chat-content__empty-content">
                            <RobotOutlined className="chat-content__empty-icon" />
                            <Text type="secondary">请选择或创建一个对话开始聊天</Text>
                        </div>
                    </div>
                ) : conversation.messages.length === 0 ? (
                    <div className="chat-content__empty">
                        <div className="chat-content__empty-content">
                            <RobotOutlined className="chat-content__empty-icon" />
                            <Text type="secondary">暂无消息，开始你的第一条消息吧</Text>
                        </div>
                    </div>
                ) : (
                    <List
                        className="chat-content__message-list"
                        itemLayout="vertical"
                        dataSource={conversation.messages}
                        renderItem={(message) => (
                            <List.Item key={message.id} className="chat-content__message-item">
                                {renderMessageContent(message)}
                            </List.Item>
                        )}
                    />
                )}
                <div ref={messagesEndRef} />
            </div>

            {/* 输入区域 */}
            <div className="chat-content__input-area">
                <div className="chat-content__input-wrapper">
                    <TextArea
                        ref={inputRef}
                        value={inputValue}
                        onChange={(e) => setInputValue(e.target.value)}
                        onKeyPress={handleKeyPress}
                        onCompositionStart={() => setIsComposing(true)}
                        onCompositionEnd={() => setIsComposing(false)}
                        placeholder={isConnected ? "输入消息..." : "等待连接..."}
                        autoSize={{ minRows: 1, maxRows: 4 }}
                        className="chat-content__input"
                        disabled={!isConnected || !conversation}
                    />
                    <Tooltip title={!isConnected ? "等待连接" : !conversation ? "请选择对话" : "发送消息 (Enter)"}>
                        <Button
                            type="primary"
                            icon={<SendOutlined />}
                            onClick={handleSend}
                            disabled={!inputValue.trim() || !isConnected || !conversation}
                            className="chat-content__send-btn"
                        >
                            发送
                        </Button>
                    </Tooltip>
                </div>
                
                {/* 连接状态提示 */}
                {!isConnected && (
                    <div className="chat-content__status-tip">
                        <Text type="warning">连接断开，请检查网络连接</Text>
                    </div>
                )}
            </div>

            {/* 编辑弹窗 */}
            <Modal
                title="编辑消息内容"
                open={editModalVisible}
                onCancel={handleCancelEdit}
                footer={[
                    <Button key="cancel" onClick={handleCancelEdit}>
                        取消
                    </Button>,
                    <Button key="submit" type="primary" onClick={handleSubmitEdit}>
                        提交
                    </Button>
                ]}
                width={600}
            >
                <TextArea
                    value={editContent}
                    onChange={(e) => setEditContent(e.target.value)}
                    placeholder="请输入编辑内容..."
                    autoSize={{ minRows: 4, maxRows: 10 }}
                    style={{ marginBottom: 16 }}
                />
            </Modal>
        </div>
    );
};

export default ChatContent;